package com.example.springboot_app.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot_app.pojo.Users;
import com.example.springboot_app.service.IUsersService;
import com.example.springboot_app.util.JwtUtils;
import com.example.springboot_app.util.RedisUtils;
import com.example.springboot_app.vo.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author svblack
<<<<<<< HEAD
 * @since 2024-09-19
=======
 * @since 2024-09-20
>>>>>>> a6b71443a1248beed4469bbfd2dae52fa8d26a93
 */
@RestController
@RequestMapping("/users")
public class UsersController {


    @Autowired
    IUsersService usersService;
    @Autowired
    RedisUtils redisUtils;


    @Value("${uploadPath}")
    String uploadPath;

    @RequestMapping("login")
    ResponseMsg login(@RequestBody Users user){
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        wrapper.eq("password", user.getPassword());
        Users result = usersService.getOne(wrapper);
        if(result==null){
            return ResponseMsg.loginFail();
        }
        //jwt tokem 唯一标识
        String uuid = UUID.randomUUID().toString();
        String subject="{'user_id':"+result.getUser_id()+",'username':'"+result.getUsername()+"'}";
        String jwtToken= JwtUtils.createJWT(uuid, subject, 1000*60*30);

        redisUtils.set(jwtToken,result,1800);
        // redisUtils.hset("jwt",jwtToken,result);//hash类型

//        return ResponseMsg.loginSuccess(jwtToken);

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("user_id", result.getUser_id());
        userInfo.put("username", result.getUsername());
        userInfo.put("avatar", result.getAvatar()); // 假设用户模型中有avatar字段

        return ResponseMsg.loginSuccess(jwtToken, userInfo);
    }




    @RequestMapping("uploadImgs")
    ResponseMsg uploadImgs(MultipartFile file){

        String fileName = "";
        //得到服务器运行绝对路径
        File aFile = null;
        try {
            aFile = ResourceUtils.getFile("classpath:");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        String path = aFile.getAbsolutePath() + "/upload/";
        String path = uploadPath ;
        System.out.println("上传绝对路径:" + path);
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir(); //upload文件夹不存在就创建
        }
        if (null != file && !file.isEmpty()){
            //file.getOriginalFilename(); //得到上传文件的原始名字
            fileName = formateDate()  + file.getOriginalFilename();
            File savedFile = new File(path + fileName); //path+fileName文件的完整路径
            System.out.println(path + fileName);
            try {
                file.transferTo(savedFile); //保存文件对象到服务器本地磁盘
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResponseMsg.success(fileName);
    }


    String formateDate(){
        LocalDateTime now = LocalDateTime.now(); //得到当前日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        return formatter.format(now);
    }


    @RequestMapping("addUsers")
    Integer doAdd(@RequestBody Users users){
        users.setAvatar("/uploads/"+users.getAvatar());
        return usersService.save(users)?0:1;
    }





}

